package com.mangowang.module.main.ui;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ScrollView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.mangowang.lib.common.help.GlideHelper;
import com.mangowang.module.main.R;

public class ImageFragment extends Fragment {

    private String pic;
    private ImageView viewById;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        pic = bundle.getString("pic");
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.iamge_fragment, container, false);
        viewById = view.findViewById(R.id.iv_image);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        Log.e("pic",pic);
        super.onViewCreated(view, savedInstanceState);
        Glide.with(getActivity())
                .asBitmap()
                .load(pic)
                .skipMemoryCache(true)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        float width = resource.getWidth();//图片原始宽度
                        float height = resource.getHeight();//图片原始高度
                        float scaledW = viewById.getMeasuredWidth();
                        float scaledH = scaledW / width * height;
                        ScrollView.LayoutParams lp = (ScrollView.LayoutParams) viewById.getLayoutParams();
                        lp.height = (int) scaledH;
                        viewById.setLayoutParams(lp);
                        GlideHelper.INSTANCE.loadImage(getActivity(),viewById, pic,10);
                    }
                });


    }

    public static void fitImage(Activity activity, ImageView imageView, float picWidth, float picHeight) {
        WindowManager wm = activity.getWindowManager();
        int width = wm.getDefaultDisplay().getWidth();
        float height = (float) width / picWidth * picHeight;
        ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
        layoutParams.height = (int) height;
        imageView.setLayoutParams(layoutParams);
    }

}
